import { useEffect, useState, useMemo } from "react";
import { Tabs, Space, Card, Button } from "antd";
import Search from "@/components/Search";
import Sheet from "@/components/Sheet";
import { useDispatch } from "react-redux";
import { setShowBtnTool } from "@/store/modules/style";
import { wareHouseAPI } from "@/apis";
import BtnTool from "@/components/BtnTool";
import ExcelExporter from '@/utils/exportToExcel';
const items = [
    {
        key: '1',
        label: '基本工商信息',
        type: 'gsxx',
        columns: [
            { key: 'GSMC', title: '公司名称', dataIndex: 'GSMC' },
            { key: 'TYSHXYDM', title: '统一社会信用代码', dataIndex: 'TYSHXYDM' },
            { key: 'FDDBR', title: '法定代表人', dataIndex: 'FDDBR' },
            { key: 'DJZT', title: '存续状态', dataIndex: 'DJZT' },
            { key: 'CLRQ', title: '成立时间', dataIndex: 'CLRQ', render: (_, record) => record.CLRQ?.slice(0, 10) },
            { key: 'HZRQ', title: '核准日期', dataIndex: 'HZRQ', render: (_, record) => record.HZRQ?.slice(0, 10) },
            { key: 'ZZZB', title: '注册资本', dataIndex: 'ZZZB' },
            { key: 'LXDH', title: '联系电话', dataIndex: 'LXDH' },
            { key: 'IS_CYDW', title: '是否成员单位', dataIndex: 'IS_CYDW', render: (_, r) => r.IS_CYDW === 1 ? '是' : '否' },
            { key: 'YX', title: '邮箱', dataIndex: 'YX' },
            { key: 'ZCDZ', title: '公司地址', dataIndex: 'ZCDZ' },
            { key: 'JYFW', title: '经营范围', dataIndex: 'JYFW' }
        ]
    },
    {
        key: '2',
        label: '高管股东信息',
        type: 'ggxx',
        columns: [
            { key: 'NAME', title: '股东名称', dataIndex: 'NAME' },
            { key: 'GSMC', title: '公司名称', dataIndex: 'GSMC' },
            { key: 'POS', title: '职位', dataIndex: 'POS' },
            { key: 'ZGJE', title: '占股金额', dataIndex: 'ZGJE' },
            { key: 'ZGBL', title: '占股比例', dataIndex: 'ZGBL' }
        ]
    },
    {
        key: '3',
        label: '实际控制人',
        type: 'sjkzr',
        columns: [
            { key: 'NAME', title: '控制人名称', dataIndex: 'NAME' },
            { key: 'RATIO', title: '占股比例', dataIndex: 'RATIO' },
            { key: 'GSMC', title: '公司名称', dataIndex: 'GSMC' }
        ]
    }
];

export default function Gongshangxinxi() {
    const [activeKey, setActiveKey] = useState('1');
    const [searchParams, setSearchParams] = useState({
                                                    '1': { company: '' },
                                                    '2': { company: '' },
                                                    '3': { company: '' }
                                                    });
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [resultData, setResultData] = useState({
        '1': { data: [], total: 0, loading: false },
        '2': { data: [], total: 0, loading: false },
        '3': { data: [], total: 0, loading: false },
    });
    const [pagination, setPagination] = useState({
        '1': { pageNum: 1, pageSize: 10 },
        '2': { pageNum: 1, pageSize: 10 },
        '3': { pageNum: 1, pageSize: 10 },
    });
    const dispatch = useDispatch();

    const currentTab = useMemo(() => items.find(tab => tab.key === activeKey), [activeKey]);

    const fetchData = async (tabKey, type) => {
        try {
            setResultData(prev => ({ ...prev, [tabKey]: { ...prev[tabKey], loading: true } }));
            
            const { pageNum, pageSize } = pagination[tabKey];
            const res = await wareHouseAPI({
                dataType: type,
                pageNum,
                pageSize,
                ...searchParams[tabKey]
            });

            setResultData(prev => ({
                ...prev,
                [tabKey]: {
                    data: res?.data?.info || [],
                    total: res?.data?.total || 0,
                    loading: false
                }
            }));
        } catch (error) {
            setResultData(prev => ({
                ...prev,
                [tabKey]: { ...prev[tabKey], loading: false }
            }));
        }
    };

    useEffect(() => {
        if (currentTab) fetchData(activeKey, currentTab.type);
    }, [activeKey, pagination[activeKey].pageNum, pagination[activeKey].pageSize, searchParams]);

    const handleTabChange = key => {
        setSelectedRowKeys([]);
        setActiveKey(key);
        dispatch(setShowBtnTool(false));
    };

    // const handleSearch = value => {
    //     setSearchParams(prev => ({ ...prev, company: value }));
    // };
    const handleSearch = value => {
        setPagination(prev => ({
            ...prev,
            [activeKey]: { ...prev[activeKey], pageNum: 1 }
        }));
        
        setSearchParams(prev => ({ 
            ...prev,
            [activeKey]: {...prev[activeKey], company: value.keyword }
        }));        
    };
    useEffect(() => {
        console.log("searchParams 改变：", searchParams);
    }, [searchParams]);

    const handlePage = (pageNum, pageSize) => {
        setPagination(prev => ({
            ...prev,
            [activeKey]: { pageNum, pageSize }
        }));
    };

    const handleSelChange = (selectedRowKeys) => {
        setSelectedRowKeys(selectedRowKeys);
        dispatch(setShowBtnTool(selectedRowKeys.length > 0));
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: handleSelChange,
    };

    const handleDel = () => {
        console.log('删除选中项:', selectedRowKeys);
        // 实际删除逻辑
    };
    const headers = currentTab.columns.map(item => ({
        key: item.dataIndex,
        label: item.title,
      }));

    const fileMap = {
        gsxx: '工商信息.xlsx',
        sjkzr: '实际控制人.xlsx',
        ggxx: '高管股东信息.xlsx',
      }

    return (
        <div>
            <h2 className="headline">工商信息</h2>
            <Tabs
                type="card"
                activeKey={activeKey}
                items={items}
                onChange={handleTabChange}
            />
            <Space direction="vertical" size={16} style={{ width: "100%" }}>
                <Search onSearch={handleSearch} />
                <Card className="table-container">
                    <div className="tableHeader">
                        <h3>明细表</h3>
                         {/* <ExcelExporter
                                data={resultData[activeKey].data}
                                headers={headers}
                                fileName={fileMap[currentTab.type]}
                                //buttonText="下载工商信息表"
                                type="primary"
                                className="btnSuccess"
                                // style={{ padding: '10px 20px' }}
                        /> */}
                        <ExcelExporter
                        onRequestData={async () => {
                            const res = await wareHouseAPI({
                            dataType: currentTab.type,
                            pageNum: 0,
                            pageSize: 0,
                            ...searchParams[activeKey]
                            });
                            return res?.data?.info || [];
                        }}
                        headers={headers}
                        fileName={fileMap[currentTab.type]}
                        type="primary"
                        className="btnSuccess"
                        />                        
                    </div>
                    <Sheet
                        columns={currentTab?.columns || []}
                        dataSource={{
                            data: resultData[activeKey].data,
                            total: resultData[activeKey].total
                        }}
                        rowSelection={rowSelection}
                        rowKey={record => {
                            if (activeKey === '1') return record.TYSHXYDM;
                            if (activeKey === '2') return `GG_${record.ID}`;
                            return `KZR_${record.NAME}_${record.GSMC}`;
                        }}
                        page={{
                            pageNum: pagination[activeKey].pageNum,
                            pageSize: pagination[activeKey].pageSize
                        }}
                        scroll={{ x: 'max-content' }}
                        loading={resultData[activeKey].loading}
                        onChange={handlePage}
                    />
                </Card>
            </Space>
            <BtnTool
                total={`已选择 ${selectedRowKeys.length} 项`}
                isShow={selectedRowKeys.length > 0}
                isSave={false}
                onDel={handleDel}
            />
        </div>
    );
}


// import { Alert, Breadcrumb, Button, Card, Modal, Popover, Space, Tabs, Typography } from "antd";
// import Search from "@/components/Search";
// import Sheet from "@/components/Sheet";
// import dayjs from "dayjs";
// import { useState } from "react";
// import { useNavigate } from "react-router-dom";
// // import UploadCom from "@/components/UploadCom";
// import BtnTool from "@/components/BtnTool";
// import { useDispatch } from "react-redux";
// import { setShowBtnTool } from "@/store/modules/style";
// import Person from "@/components/Person";
// import State from "@/components/State";
// import { SettingOutlined } from "@ant-design/icons";
// import Setable from "@/components/Setable";
// import WordShow from "@/components/WordShow";
// import ExcelExporter from '@/utils/exportToExcel';
// const items = [
//     {
//         key: '1',
//         label: '基本工商信息',
//         dataIndex: '',
//     },
//     {
//         key: '2',
//         label: '高管股东信息',
//         dataIndex: <div className="tab-content">这里是股东信息内容...</div>,
//     },
//     {
//         key: '3',
//         label: '实际控制人',
//         dataIndex: <div className="tab-content">这里是司法风险内容...</div>,
//     }
// ];

// const dataSource = {
//     total: 46,
//     data: Array.from({
//         length: 46,
//     }).map((_, i) => ({
//         key: i,
//         batch: `P202408-00${i}`,
//         creator: '章三',
//         time: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
//         company: '成都九鼎科技（集团）有限公司',
//         state: '存续',
//         person: '王洪涛',
//         scale: '超大型',
//         jyfw: '经营范围'.repeat(
//             20,
//         )
//     }))
// };
// export default function Gongshangxinxi() {

//     const defaultColumns = [
//         {
//             title: '导入批次',
//             dataIndex: 'batch',
//             sorter: (a, b) => a.batch.localeCompare(b.batch),
//         },
//         {
//             title: '创建人',
//             dataIndex: 'creator',
//             render: (dom, rowData, index) => {
//                 return <Person text={rowData.creator} />
//             },
//         },
//         {
//             title: '创建时间',
//             dataIndex: 'time',
//             sorter: (a, b) => a.time - b.time,
//         },
//         {
//             title: '公司名称',
//             dataIndex: 'company',
//         },
//         {
//             title: '登记状态',
//             dataIndex: 'state',
//             render: (text) => <State text={text} />
//         },
//         {
//             title: '法定代表人',
//             dataIndex: 'person',
//             render: (text) => {
//                 return <Person text={text} />
//             }
//         },
//         {
//             title: '企业规模',
//             dataIndex: 'scale'
//         }
//     ]
//     const [columns, setColumns] = useState(defaultColumns)
//     const [page, setPage] = useState({ pageNum: 1, pageSize: 10 })
//     const navigate = useNavigate()
//     const [selectedRowKeys, setSelectedRowKeys] = useState([]);
//     const dispatch = useDispatch()
//     const onChange = (key) => {
//         console.log(key);
//     };
//     // 状态参数
//     const [activeKey, setActiveKey] = useState('1');
//     const handleSearch = (val) => {
//         console.log(val)
//     }
//     // 分页
//     const handlePage = (pageNum, pageSize) => {
//         setPage({
//             pageNum,
//             pageSize
//         })
//     }
//     const getData = () => {
//         return {
//             data: dataSource
//         }
//     }
//     // 表格选择
//     const handleSelChange = (selectedRowKeys, selectedRows) => {
//         // console.log(selectedRowKeys, selectedRows)
//         setSelectedRowKeys(selectedRowKeys)
//         dispatch(setShowBtnTool(selectedRowKeys.length > 0))
//     }
//     const rowSelection = {
//         selectedRowKeys,
//         onChange: handleSelChange,
//     };
//     const handleAdd = () => {
//         // 跳转至新页面
//         navigate('/tianyancha/new')
//     }
//     const handleDel = () => {
//         // 删除接口
//         console.log('删除')
//     }
//     const handleChange = (result) => {
//         setColumns(result)
//     }
//     const [open, setOpen] = useState(false)
//     return (
//         <div>
//             <h2 className="headline">工商信息</h2>
//             <Tabs activeKey={activeKey} items={items} onChange={setActiveKey}  />
//             <Space direction="vertical" size={16} style={{ width: "100%" }}>
//                 <Search onSearch={handleSearch}></Search>
//                 <Card className="table-container">
//                     <div className="tableHeader">
//                         <h3>明细表</h3>
//                         <div>
//                             <Button type="primary" onClick={handleAdd}>新建</Button>
//                             {/* <Button type="primary" danger onClick={}>删除</Button> */}
//                             <Button type="primary" onClick={() => setOpen(true)} className="btnSuccess">Excel导入</Button>
//                             <ExcelExporter
//                                 data={dataSource.data}
//                                 headers={defaultColumns.map(item => ({
//                                     key: item.dataIndex,
//                                     label: item.title
//                                 }))}
//                                 fileName="工商信息.xlsx"
//                                 //buttonText="下载工商信息表"
//                                 type="primary"
//                                 className="btnSuccess"
//                                 // style={{ padding: '10px 20px' }}
//                             />
//                             {/* <Popover placement="bottomLeft" content={<Setable datas={columns} handleChange={handleChange} />} trigger="click" arrow={false}>
//                                 <Button color="default" variant="link" icon={<SettingOutlined />}></Button>
//                             </Popover> */}
//                         </div>
//                     </div>
//                     <Sheet columns={columns} dataSource={dataSource} rowSelection={rowSelection} rowKey='key' page={page} onChange={handlePage}></Sheet>
//                     {/* <Sheet columns={columns} dataSource={dataSource} rowKey="key" page={page} onChange={handlePage} rowSelection={rowSelection} ></Sheet> */}
//                     {/* <Sheet columns={columns} dataSource={getData} page={page} onChange={handlePage} rowSelection={rowSelection} isDrag={true}></Sheet> */}
//                 </Card>
//             </Space>
//             {/* <Modal title="上传文件" centered
//                 open={open}
//                 onCancel={() => setOpen(false)}
//                 width={1000}
//                 footer={null}>
//                 <UploadCom></UploadCom>
//             </Modal> */}
//             {<BtnTool total={`已选择 ${selectedRowKeys.length} 项`} isShow={selectedRowKeys.length > 0} isSave={false} onDel={handleDel}></BtnTool>}
//         </div>
//     )
// }